# from langgraph.graph import StateGraph, add_messages
# from typing_extensions import TypedDict, Annotated, List
# from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
# from langchain_openai import ChatOpenAI
# import operator
# import os

# # 尝试获取环境变量
# api_key = os.getenv('DEEPSEEK_API_KEY')
# if api_key is None:
#     print("错误：未找到环境变量 DEEPSEEK_API_KEY。请检查是否已正确设置。")
#     exit(1)
# else:
#     print("环境变量 DEEPSEEK_API_KEY 已找到。")

# llm = ChatOpenAI(
#     model='deepseek-chat',
#     base_url='https://api.deepseek.com/v1',
#     api_key=api_key
# )

# msg1 = HumanMessage(content='你好，你是谁啊', id='1')
# msg2 = AIMessage(content='我是一个智能体，我叫DeepSeek，你可以用我来完成你的任务', id='2')
# print(add_messages([msg1, msg2]))
from langgraph.graph import StateGraph,add_messages,START,END
from typing_extensions import TypedDict,Annotated,List
from langchain_core.messages import HumanMessage,AIMessage,SystemMessage
from langchain_openai import ChatOpenAI
import operator

import os 

# api_key = os.getenv('DEEPSEEK_API_KEY')
llm =ChatOpenAI(
    model='deepseek-chat',
    base_url='https://api.deepseek.com/v1',
    api_key=os.environ['DEEPSEEK_API_KEY']
)
class State(TypedDict):
    messages:Annotated[List,add_messages]
builder =StateGraph(State)
def chat_node(State):
    return {'messages':llm.invoke(State['messages'])}
builder.add_node('chat_node',chat_node)
builder.add_edge(START,'chat_node')
builder.add_edge('chat_node',END)
graph = builder.compile()
# query='你好，你是谁啊'
# response = graph.invoke({'messages':[HumanMessage(content=query)]})
# print(response['messages'])
def stream_graph_updates(user_input: str):  
    for event in graph.stream({"messages": [("user", user_input)]}):
        for value in event.values():
            print("模型回复:", value["messages"][-1].content)
            
def chat(user_input: str):
    response = graph.invoke({'messages':[HumanMessage(content=user_input)]})
    return response['messages'][-1].content

while True:
    try:
        user_input = input('-'*50+"\n用户提问: ")
        if user_input.lower() in ["退出"]:
            print("下次再见！")
            break

        print('-'*10+"\n模型回复:",chat(user_input))
    except:
        print("出错了")
        break
